package system

import (
	"5title_gin/global"
	fileUtils "5title_gin/pkg/utils/file"
	"5title_gin/pkg/utils/http"
	"errors"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"log"
	"mime/multipart"
)

type OssService struct {
}

func NewOssService() *OssService {
	return &OssService{}
}

// UploadImg 图片上传
func (s *OssService) UploadImg(c *gin.Context) (string, error) {
	file, err := c.FormFile("makefile")
	if file != nil {
		zap.S().Info(file.Filename)
	} else {
		zap.S().Info("文件为空")
		return "", errors.New("文件为空")
	}
	if err != nil {
		http.FailWithError(err, c)
		return "", err
	}

	value, exists := c.Get("userID")
	if !exists {
		return "", errors.New("未提供有效的 Token")
	}
	userId := value.(uint)
	const (
		KB = 1024
		MB = KB * 1024
	)
	if file.Size > global.Config.Storage.Size*MB {
		return "文件大小超出限制", errors.New("文件大小超出限制")
	}
	src, err := file.Open()
	if err != nil {

		return "", err
	}
	defer func(src multipart.File) {
		err := src.Close()
		if err != nil {

		}
	}(src)

	ctx := c.Request.Context()
	if global.Storage == nil {
		log.Fatal("Storage 组件未初始化")
	}

	mimeType, err := fileUtils.GetMimeType(file.Filename)
	zap.S().Info(mimeType)
	if err != nil {
		return "", err
	}
	url, err := global.Storage.UploadFile(ctx, src, file.Filename, mimeType)
	if err != nil {
		return "", err
	}
	// 更新数据库中的头像
	result := global.DB.Table("user_models").Where("id = ?", userId).Update("avatar", url)
	if result.Error != nil {
		return "更新用户头像失败", result.Error
	}
	if result.RowsAffected == 0 {
		return "", errors.New("用户不存在")
	}
	return url, nil
}
